package ctrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import service.Impl.IBookServiceImpl;
import service.Impl.IWishListLineServiceImpl;
import service.Impl.IWishListServiceImpl;
import vo.Book;
import vo.Client;
import vo.WishList;
import vo.WishListLine;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ShowWishListServlet")
public class ShowWishListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        IWishListServiceImpl wishListService = new IWishListServiceImpl();
        IWishListLineServiceImpl wishListLineService = new IWishListLineServiceImpl();
        IBookServiceImpl bookService = new IBookServiceImpl();

        HttpSession session = request.getSession();
        Client client = (Client) session.getAttribute("client");

        WishList wishList = wishListService.getWishListByUserId(client.getId());
        List<WishListLine> wishes = wishListLineService.getWishesByWishListId(wishList.getId());
        JSONArray bookJA = new JSONArray();
        for(WishListLine w: wishes){
            Book book = bookService.selectBookById(w.getBookId());
            JSONObject jo = new JSONObject();
            jo.put("id", w.getId());
            jo.put("bookId", w.getBookId());
            jo.put("name",book.getName());
            jo.put("breifIntro",book.getBriefIntro());
            jo.put("price",book.getPrice());
            jo.put("type",book.getType());
            jo.put("imgUrl",book.getImgUrl());
            bookJA.add(jo);
        }
        response.getWriter().write(String.valueOf(bookJA));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
